package com.itdct.mto.core.manager;

import com.itdct.mto.core.bo.IndexBo;
import com.itdct.mto.core.bo.TableBo;
import com.itdct.mto.core.manager.base.BaseTableConvertManager;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Zhouwx
 * @date 2025/7/7 10:05:31
 * @version 1.0
 * @description
 */
@ConditionalOnProperty(name = "mto.database-mode", havingValue = "B")
@Slf4j
@Component
public class BTableConvertManager extends BaseTableConvertManager {

    @Override
    public String generateTableDdl(TableBo tableBo) {
        String tableDdl = tableBo.getTableDdl();
        if (mtoConfig.isMysqlToMysql()) {
            // INFO: Zhouwx: 2025/7/7 如果是MySQL转MySQL，则后面的变更工作是不需要的
            return tableDdl;
        }

        // INFO: Zhouwx: 2025/7/7 索引名必须要修改，不然进入OpenGauss是全局索引，索引名称重复会报错
        ArrayList<IndexBo> indexList = tableBo.getIndexList();
        String tableName = tableBo.getTableName();
        for (IndexBo indexBo : indexList) {
            String indexType = indexBo.getIndexType();
            if (indexType.equals("KEY") || indexType.equals("UNIQUE KEY")) {
                String indexName = indexBo.getIndexName().replace("`", "").trim();
                String pgIndexName = tableName + "__" + indexName;
                if (pgIndexName.length() > 63) {
                    pgIndexName = pgIndexName.substring(pgIndexName.length() - 63);
                }
                tableDdl = tableDdl.replace("`" + indexName + "`", "`" + pgIndexName + "`");
            }

        }
        return tableDdl;
    }
}
